package phone.qyg.com.qyg.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.app.adapter.recycler.CommonAdapter;
import com.app.adapter.recycler.MultiItemTypeAdapter;
import com.app.adapter.recycler.RecycleViewDivider;
import com.app.adapter.recycler.base.ViewHolder;
import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.OptionImageUtils;
import com.app.utils.PromptManager;
import com.app.utils.SharePrefUtil;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;
import com.app.view.BaseViewStateLayout;
import com.app.xutils.MyCallBack;
import com.app.xutils.Xutils;
import com.liaoinstan.springview.container.AliFooter;
import com.liaoinstan.springview.container.AliHeader;
import com.liaoinstan.springview.widget.SpringView;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.MessageFormat;
import java.util.List;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Activity;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.utils.PopuRecycle;

/**
 * 作者：lblbh on 2017/11/29 16:31
 * 邮箱：lanbuhan@163.com
 * 功能：文化活动 列表
 */
@ContentView(R.layout.act_list)
public class ActivityListActivity extends BaseActivity {

    String TIME_STATE = "{0} <font color='{1}'>{2}</font>";
    String ACT_COUNT = "<font color='#ff6633'>{0}</font>/{1}";

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.find)
    TextView find;

    @ViewInject(R.id.act_one)
    TextView act_one;

    @ViewInject(R.id.act_two)
    TextView act_two;

    @ViewInject(R.id.act_there)
    TextView act_there;

    @ViewInject(R.id.act_four)
    TextView act_four;

    @ViewInject(R.id.act_five)
    TextView act_five;

    @ViewInject(R.id.recycler_mode)
    TextView recycler_mode;

    SpringView springview;

    @ViewInject(R.id.linear)
    LinearLayout linear;

    BaseViewStateLayout baseView;

    PopupWindow popupWindow;

    RecyclerView recycler;

    List<Base> citys;//城市列表

    List<Base> types;//类别列表

    List<Base> states;//状态列表

    List<Base> times;//预约时间列表

    List<Base> sorts;//排序列表

    Base city;//城市

    Base type;//类别

    Base state;//状态

    Base time;//时间

    Base sort;//排序

    List<Activity> models;

    CommonAdapter adapter;

    String recyeMode;

    boolean isForce;

    int page_no,totalpage;


    @Override
    public void initData(Bundle savedInstanceState) {

        initType();

        recyeMode = SharePrefUtil.getString(SharePrefUtil.KEY.ACT_MODE,ApplicationConfig.RECYCLE_LIST);

        CommonUtil.setTextViewDrawableDirection(recycler_mode,
                                                4,
                                                (recyeMode.equals(ApplicationConfig.RECYCLE_LIST)?
                                                        R.drawable.recycle_list:
                                                        R.drawable.recycle_grid));

        baseView = new BaseViewStateLayout(QXApplication.getContext()) {

            @Override
            public View obtionView() {
                View sucessView = View.inflate(QXApplication.getContext(), R.layout.base_spring_recycler,null);
                recycler = (RecyclerView) sucessView.findViewById(R.id.recycler);
                springview = (SpringView) sucessView.findViewById(R.id.springview);

                springview.setListener(new SpringView.OnFreshListener() {
                    @Override
                    public void onRefresh() {
                        isForce = true;
                        getInitNetwork(false);
                    }

                    @Override
                    public void onLoadmore() {
                        if(isRequestList(models) && (page_no < totalpage) ){
                            getInitNetwork(true);
                        }else{
                            PromptManager.showToast(R.string.more_no_datas);
                            springview.onFinishFreshAndLoad();
                        }

                    }
                });

                springview.setHeader(new AliHeader(QXApplication.getContext(),false));
                springview.setFooter(new AliFooter(QXApplication.getContext(),false));
                return sucessView;
            }

            @Override
            public Object obtionData() {
                return DELFAUTSTATE;
            }
        };

        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        linear.addView(baseView,layoutParams);
        x.view().inject(linear);


    }


    /**
     * 执行网络请求
     */
    private void getInitNetwork(final boolean isPull){


        if(isPull){
            page_no = page_no + 1;
        }else{
            page_no = 1;
        }

        if(isForce){
            page_no = 1;
        }


        mapKeys.put(AppHttpKey.COUNTRY_ID,themeItemId(city));
        mapKeys.put(AppHttpKey.ACT_TYPE,themeItemId(type));
        mapKeys.put(AppHttpKey.ACT_STATUS,themeItemId(state));
        mapKeys.put(AppHttpKey.APPLY_TIME,themeItemId(time));
        mapKeys.put(AppHttpKey.INTELL_SORT,themeItemId(sort));
        mapKeys.put(AppHttpKey.PAGE_NO,String.valueOf(page_no));

        Xutils.Get(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.CULTURE_ACT_LIST,
                mapKeys,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);

                        List<Activity> temps = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.ACT_LIST, Activity.class);

                        totalpage = JSONTool.requestJSONfindNameCount(result,JSONTool.Enum.DATA,JSONTool.Enum.TOTALPAGE);

                        if(!isRequestList(temps) && !isPull){
                            baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_EMPTY);
                            baseView.stateView();
                            return;
                        }
                        //成功获取到数据
                        baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_SUCESS);
                        baseView.stateView();

                        setModelData(isPull,temps);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_ERROE);
                        baseView.stateView();
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                        springview.onFinishFreshAndLoad();
                    }
                });
    }


    private void setModelData(final boolean isPull, List<Activity> temps) {
        if ((adapter == null && isRequestList(temps)) || isForce) {
            isForce = false;

            //数据初始化工作
            models = temps;

            int layou = (ApplicationConfig.RECYCLE_LIST.equals(recyeMode))?R.layout.item_act_list:R.layout.item_act_grid;

            final CommonAdapter adapter = new CommonAdapter<Activity>(QXApplication.getContext(),layou,models) {
                @Override
                protected void convert(ViewHolder holder, final Activity model, int position) {


                    holder.setText(R.id.item_title,model.title);
                    holder.setImage(R.id.item_img,model.fixImgUrl, OptionImageUtils.getRectRatioAct());
                    if(ApplicationConfig.RECYCLE_LIST.equals(recyeMode)){
                        holder.setText(R.id.item_address,model.startTime);
                        holder.setText(R.id.item_state,model.statusName);
                        holder.setText(R.id.item_map,model.address);
                        holder.setTextColor(R.id.item_state,model.color);
//                        holder.setTextDrawStroke(R.id.item_state,model.color);
                    }else{
                        holder.setText(R.id.subscribe,model.statusName);
                        holder.setText(R.id.item_address,model.address);
                        holder.setTextHTMLTwo(R.id.item_time_state, MessageFormat.format(TIME_STATE,model.startTime,model.color,model.statusName));
                        String remainQuota = model.remainQuota;
                        String[] remain = remainQuota.split("/");
                        if(remain.length>=2){
                            holder.setTextHTMLTwo(R.id.item_number, MessageFormat.format(ACT_COUNT,remain[0],remain[1]));
                        }else{
                            holder.setText(R.id.item_number,remainQuota);
                        }
                        holder.setText(R.id.subscribe,model.applyBtnName);
                        holder.setTextColor(R.id.subscribe,model.applyBtnColor);
                        holder.setTextDrawStroke(R.id.subscribe,model.applyBtnColor);

                        holder.setOnClickListener(R.id.subscribe, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                TransformController.transformControllerModel(QXApplication.getContext(), ActivityRegisActivity.class,model);
                            }
                        });
                    }

                }
            };

            adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    SystemPrintl.systemPrintl("我在点击活动--->>>"+position);
                    Object obj = adapter.getDatas().get(position);
                    TransformController.transformControllerModel(QXApplication.getContext(), ActivityDetailActivity.class,obj);
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }
            });

            setRecyeMode();

            recycler.setAdapter(adapter);

        }

        if (isPull && isRequestList(models) && isRequestList(temps)) {
            //上拉加载数据
            models.addAll(temps);
        }

//        //刷新数据
        if (adapter != null)
            adapter.notifyDataSetChanged();
    }


    private void initType(){
        Xutils.Get(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.ACT_SELECT_CONDITION,
                mapKeys,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        citys = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.AREA_LIST,Base.class);
                        types = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.ACT_TYPE_LIST,Base.class);
                        states = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.STATUS_LIST,Base.class);
                        times = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.DATE_LIST,Base.class);
                        sorts = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.SORT_LIST,Base.class);

                        if(isRequestList(citys)){
                            city = citys.get(0);
                            act_one.setText(city.title);
                        }

                        if(isRequestList(types)){
                            type = types.get(0);
                            act_two.setText(type.title);
                        }

                        if(isRequestList(states)){
                            state = states.get(0);
                            act_there.setText(state.title);
                        }


                        if(isRequestList(times)){
                            time = times.get(0);
                            act_four.setText(time.title);
                        }

                        if(isRequestList(sorts)){
                            sort = sorts.get(0);
                            act_five.setText(sort.title);
                        }


                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                        getInitNetwork(false);
                    }
                });
    }


    @Event(value = {R.id.back,R.id.find,R.id.act_one,R.id.act_two,
                    R.id.act_there,R.id.act_four,R.id.act_five,
                    R.id.recycler_mode})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.find:
                TransformController.transformControllerModel(QXApplication.getContext(),
                        AppFindActivity.class,
                        new Base(QXApplication.getContext().getString(R.string.act)));
                break;
            case R.id.act_one:
                if(!isRequestList(citys)){
                    PromptManager.showToast(R.string.city_county_hint);
                    return;
                }
                if(popupWindow!=null && popupWindow.isShowing()){
                    popupWindow.dismiss();
                    return;
                }
                popupWindow = PopuRecycle.setPopuThemes(this,v, citys,city, new PopuRecycle.OnClickState() {
                    @Override
                    public void OnItemClick(Object model, PopuRecycle.EnumType enumType) {
                        Base base = (Base) model;
                        if(city != base) {
                            city = base;
                            act_one.setText(city.title);
                            isForce = true;
                            getInitNetwork(false);
                        }
                    }
                });
                break;
            case R.id.act_two:
                if(!isRequestList(types)){
                    PromptManager.showToast(R.string.act_county_hint);
                    return;
                }
                if(popupWindow!=null && popupWindow.isShowing()){
                    popupWindow.dismiss();
                    return;
                }
                popupWindow = PopuRecycle.setPopuThemes(this,v, types,type, new PopuRecycle.OnClickState() {
                    @Override
                    public void OnItemClick(Object model, PopuRecycle.EnumType enumType) {
                        Base base = (Base) model;
                        if(type != base) {
                            type = base;
                            act_two.setText(type.title);
                            isForce = true;
                            getInitNetwork(false);
                        }
                    }
                });
                break;
            case R.id.act_there:
                if(!isRequestList(states)){
                    PromptManager.showToast(R.string.act_state_hint);
                    return;
                }
                if(popupWindow!=null && popupWindow.isShowing()){
                    popupWindow.dismiss();
                    return;
                }
                popupWindow = PopuRecycle.setPopuThemes(this,v, states,state, new PopuRecycle.OnClickState() {
                    @Override
                    public void OnItemClick(Object model, PopuRecycle.EnumType enumType) {
                        Base base = (Base) model;
                        if(state != base) {
                            state = base;
                            act_there.setText(state.title);
                            isForce = true;
                            getInitNetwork(false);
                        }
                    }
                });
                break;
            case R.id.act_four:
                if(!isRequestList(times)){
                    PromptManager.showToast(R.string.act_time_hint);
                    return;
                }
                if(popupWindow!=null && popupWindow.isShowing()){
                    popupWindow.dismiss();
                    return;
                }
                popupWindow = PopuRecycle.setPopuThemes(this,v, times,time, new PopuRecycle.OnClickState() {
                    @Override
                    public void OnItemClick(Object model, PopuRecycle.EnumType enumType) {
                        Base base = (Base) model;
                        if(time != base) {
                            time = base;
                            act_four.setText(time.title);
                            isForce = true;
                            getInitNetwork(false);
                        }
                    }
                });
                break;
            case R.id.act_five:
                if(!isRequestList(sorts)){
                    PromptManager.showToast(R.string.act_sort_hint);
                    return;
                }
                if(popupWindow!=null && popupWindow.isShowing()){
                    popupWindow.dismiss();
                    return;
                }
                popupWindow = PopuRecycle.setPopuThemes(this,v, sorts,sort, new PopuRecycle.OnClickState() {
                    @Override
                    public void OnItemClick(Object model, PopuRecycle.EnumType enumType) {
                        Base base = (Base) model;
                        if(sort != base) {
                            sort = base;
                            act_five.setText(sort.title);
                            isForce = true;
                            getInitNetwork(false);
                        }
                    }
                });
                break;
            case R.id.recycler_mode:
//                recyeMode = SharePrefUtil.getString(SharePrefUtil.KEY.ACT_MODE,ApplicationConfig.RECYCLE_LIST);
                recyeMode = (ApplicationConfig.RECYCLE_LIST.equals(recyeMode))?
                                ApplicationConfig.RECYCLE_GIRD:
                                ApplicationConfig.RECYCLE_LIST;
                SharePrefUtil.saveString(SharePrefUtil.KEY.ACT_MODE,recyeMode);

                isForce = true;

                getInitNetwork(false);

                CommonUtil.setTextViewDrawableDirection(recycler_mode,
                                                        4,
                                                        (recyeMode.equals(ApplicationConfig.RECYCLE_LIST)?
                                                                R.drawable.recycle_list:
                                                                R.drawable.recycle_grid));
                break;
        }
    }


    private void setRecyeMode(){
        if(recycler == null) return;
        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.VERTICAL);
//        if(ApplicationConfig.RECYCLE_LIST.equals(recyeMode)){
//
//        }else{
//            recycler.addItemDecoration(new RecycleViewDivider(
//                    mContext, LinearLayoutManager.HORIZONTAL,
//                    CommonUtil.dip2px(QXApplication.getContext(),1),
//                    getResources().getColor(R.color.white)));
//        }

        recycler.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL,
                CommonUtil.dip2px(QXApplication.getContext(),1),
                getResources().getColor((ApplicationConfig.RECYCLE_LIST.equals(recyeMode))?
                        R.color.divider :
                        R.color.white)));

        recycler.setLayoutManager(layoutVerManager);
    }

    /**
     * 获取类型id
     * @return
     */
    private String themeItemId(Base base){
        String id = ApplicationConfig.ALL_TYPE_ID;
        if (base != null){
            id = String.valueOf(base.id);
        }
        return id;
    }

    @Override
    public void initViewHandler() {
    }

    @Override
    public void initSucessView() {}
}
